package com.ruoyi.auth.listener;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.RocketMQConstants;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import io.jsonwebtoken.Claims;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@RocketMQMessageListener(consumerGroup = RocketMQConstants.GROUP, topic = RocketMQConstants.TOPIC)
public class ReplaceLoginRocketMQListener implements RocketMQListener<String> {

    @Autowired
    RedisService redisService;

    @Override
    public void onMessage(String redisKey) {
        String[] redisKeys = redisKey.split("--");
        String tokenMapJsonStr = redisService.getCacheObject(redisKeys[0]);
        if (redisKeys.length == 1) {
            redisKey = redisKeys[0];
            redisKeys = new String[2];
            redisKeys[0] = redisKey;
            redisKeys[1] = "s";
        }

        if ("del".equals(redisKeys[1])) {
            redisService.setCacheObject(redisKeys[0], Constants.TOKEN_MAP_STR, 300L, TimeUnit.MINUTES);
        } else {
            if (StringUtils.isNotEmpty(tokenMapJsonStr)) {
                Map tokenMap = JSONObject.parseObject(tokenMapJsonStr, Map.class);
                if (tokenMap != null && tokenMap.size() > 0) {
                    if ((Boolean) tokenMap.get("isLogin") && (Integer) tokenMap.get("countLogin") >= 2) {
                        String accessToken = (String) tokenMap.get("access_token");
                        Claims claims = JwtUtils.parseToken(accessToken);
                        String tokenId = CacheConstants.LOGIN_TOKEN_KEY + claims.get(SecurityConstants.USER_KEY);
                        boolean delFlag = redisService.deleteObject(tokenId);
                        redisService.deleteObject(SecurityUtils.getUsername() + Constants.IS_LOGIN);
                    }
                }
            }
        }
    }
}
